﻿using Aliyun.OSS;
using Aliyun.OSS.Common;
using DataModel.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace CommonLibrary.Helper
{
    public class OssHelper
    {
        /// <summary>
        /// 上传壁纸
        /// </summary>
        /// <param name="oss"></param>
        /// <param name="localFile"></param>
        /// <returns></returns>
        public static bool PutObject(OssConfig oss, string localFile)
        {
            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret);
            try
            {
                string fileName = Path.GetFileName(localFile);
                string objectName = "test/" + fileName;

                client.PutObject(oss.Bucket, objectName, localFile);
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Put object failed, {0}", ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="oss"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[]? GetObject(OssConfig oss, string url)
        {
            var conf = new ClientConfiguration();
            //// 设置最大并发连接数。
            //ClientConfiguration.ConnectionLimit = 512;
            //// 设置请求失败后最大的重试次数。
            //conf.MaxErrorRetry = 3;
            // 设置连接超时时间。
            //conf.ConnectionTimeout = 300;

            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret, conf);
            try
            {
                var result = client.GetObject(oss.Bucket, url);
                using var requestStream = result.Content;
                using MemoryStream ms = new();
                requestStream.CopyTo(ms);
                byte[] data = ms.ToArray();

                return data;
            }
            catch (OssException ex)
            {
                Debug.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));
                return null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
                return null;
            }
            finally
            {
                
            }
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="oss"></param>
        /// <returns></returns>
        public static string[]? ListObject(OssConfig oss)
        {
            IList<string> list = [];
            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret);

            ObjectListing? result = null;
            string nextMarker = oss.PathFilter;
            do
            {
                var listObjectsRequest = new ListObjectsRequest("picture-center")
                {
                    Marker = nextMarker,
                    Prefix = oss.PathFilter,
                    //Delimiter = "/"
                };
                // 列举文件。
                result = client.ListObjects(listObjectsRequest);
                foreach (var summary in result.ObjectSummaries)
                {
                    Debug.WriteLine(summary.Key);
                    list.Add(summary.Key);
                }
                nextMarker = result.NextMarker;
            } while (result.IsTruncated);

            return [.. list];
        }
    }
}
